<template>
  <div>
    <form-dialog ref="formDrawerRef" title="服务详情" :isButton="false" top="5vh" width="90%">
      <el-button type="primary" @click="orderPrint()">打印</el-button>
      <el-popconfirm
        v-if="curInfo.status === 0"
        title="该维修单是否已完成维修？"
        width="240"
        @confirm="handleFinishOrder"
      >
        <template #reference>
          <el-button type="primary">完工</el-button>
        </template>
      </el-popconfirm>
      <el-button
        v-if="curInfo.status === 1 && curInfo.payStatus === 0"
        type="primary"
        @click="handlePayCreate()"
        >结算</el-button
      >
      <el-popconfirm
        v-if="curInfo.status === 1 && curInfo.payStatus === 1"
        title="确定该用户已取车？"
        width="240"
        @confirm="handleGetCar"
      >
        <template #reference>
          <el-button type="primary">取车</el-button>
        </template>
      </el-popconfirm>
      <div class="dialog-body">
        <el-descriptions title="基本信息" :column="3" border>
          <el-descriptions-item
            label="车主姓名"
            label-align="center"
            label-class-name="info-label"
            >{{
              curInfo.payStatus ? curInfo.customerName : curInfo.customer?.customerName
            }}</el-descriptions-item
          >
          <el-descriptions-item
            label="车主电话"
            label-align="center"
            label-class-name="info-label"
            >{{
              curInfo.payStatus ? curInfo.customerPhone : curInfo.customer.phone
            }}</el-descriptions-item
          >
          <el-descriptions-item label="车牌号" label-align="center" label-class-name="info-label">{{
            curInfo.payStatus ? curInfo.licensePlate : curInfo.car.licensePlate
          }}</el-descriptions-item>
          <el-descriptions-item
            label="车架号(vin)"
            label-align="center"
            label-class-name="info-label"
            >{{ curInfo.payStatus ? curInfo.vin : curInfo.car.vin }}</el-descriptions-item
          >
          <el-descriptions-item label="车型" label-align="center" label-class-name="info-label">{{
            curInfo.payStatus ? curInfo.vehicleModel : curInfo.car.vehicleModel
          }}</el-descriptions-item>
          <el-descriptions-item
            label="接车公里数"
            label-align="center"
            label-class-name="info-label"
            >{{
              curInfo.payStatus ? curInfo.mileageNum : curInfo.car.mileageNum
            }}</el-descriptions-item
          >
          <el-descriptions-item
            label="保险到期日期"
            label-align="center"
            label-class-name="info-label"
            >{{ curInfo.car.insuranceExpireTime }}</el-descriptions-item
          >
          <el-descriptions-item
            label="年检到期日期"
            label-align="center"
            label-class-name="info-label"
            >{{ curInfo.car.annualExpireTime }}</el-descriptions-item
          >
          <el-descriptions-item
            label="燃料(能源类型)"
            label-align="center"
            label-class-name="info-label"
            >{{
              curInfo.payStatus
                ? handleEnergyType(curInfo.energyType)
                : handleEnergyType(curInfo.car.energyType)
            }}</el-descriptions-item
          >
        </el-descriptions>
        <div class="mt-5 mb-2 text-[16px] font-bold">外观检查</div>
        <div class="grid grid-cols-4 gap-4">
          <template v-if="outItem.length > 0">
            <el-card
              v-for="item in outItem"
              :key="item.id"
              :header="item.precheckName"
              style="max-width: 280px"
            >
              <el-image
                style="width: 100px; height: 100px"
                :src="item.dangerImg"
                fit="cover"
                :preview-src-list="[item.dangerImg]"
              />
              <div>
                <el-tag type="danger">{{ item.dangerRemark }}</el-tag>
              </div>
            </el-card>
          </template>
          <el-tag v-else type="primary" class="w-[100px]">一切正常</el-tag>
        </div>
        <el-divider />
        <div class="mt-5 mb-2 text-[16px] font-bold">内饰检查</div>
        <template v-if="inItem.length > 0">
          <div class="grid grid-cols-4 gap-4">
            <el-card
              v-for="item in inItem"
              :key="item.id"
              :header="item.precheckName"
              style="max-width: 280px"
            >
              <el-image
                style="width: 100px; height: 100px"
                :src="item.dangerImg"
                fit="cover"
                :preview-src-list="[item.dangerImg]"
              />
              <div>
                <el-tag type="danger">{{ item.dangerRemark }}</el-tag>
              </div>
            </el-card>
          </div>
        </template>
        <el-tag v-else type="primary" class="w-[100px]">一切正常</el-tag>
        <el-divider />
        <div class="mt-5 mb-2 text-[16px] font-bold">
          服务项目
          <span class="ml-4"
            >合计:<span class="text-red-500">¥{{ handleTotalPrice() }}</span></span
          >
        </div>
        <template v-if="curProjectAccessoryList.length">
          <el-card class="mt-2" v-for="item in curProjectAccessoryList" :key="item.id">
            <template #header>
              <div class="flex justify-between items-center">
                <div>
                  <span class="font-bold text-base">{{ item.projectName }}</span>
                  <span class="ml-4"
                    >项目工时费:<span class="text-red-500">￥{{ item.manHourAmount }}</span>
                    <span class="ml-4"
                      >合计:<span class="text-red-500">￥{{ item.totalManHourAmount }}</span></span
                    ></span
                  >
                </div>
              </div>
            </template>
            <el-table
              v-if="item.productList && item.productList.length"
              :data="item.productList"
              :header-row-style="{ height: '40px' }"
            >
              <el-table-column label="名称" prop="productName"></el-table-column>
              <el-table-column label="数量" prop="num"> </el-table-column>
              <el-table-column label="单价" prop="saleAmount"></el-table-column>
              <el-table-column label="总价" prop="totalAmount"> </el-table-column>
            </el-table>
            <el-empty v-else description="暂无配件项目" />
          </el-card>
        </template>
        <el-empty v-else description="暂无服务项目" />
      </div>
      <form-drawer
        ref="formDrawerPayRef"
        title="结算"
        :appendToBody="true"
        @submit="handlePaySubmitOrder"
      >
        <el-form ref="formPayRef" :model="formPay" :rules="rulesPay" label-width="100px">
          <el-form-item label="结算金额" prop="actualAmount">
            <el-input
              v-model="formPay.actualAmount"
              v-number
              type="number"
              :min="1"
              placeholder="请输入结算金额"
            />
          </el-form-item>
          <el-form-item label="结算方式" prop="paySource">
            <el-select v-model="formPay.paySource" placeholder="请选择结算方式">
              <el-option label="支付宝" :value="1" />
              <el-option label="微信" :value="2" />
              <el-option label="现金" :value="3" />
            </el-select>
          </el-form-item>
        </el-form>
      </form-drawer>
    </form-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, watch } from "vue";
import useRepairStore from "@/stores/modules/repair";
import { useInitForm } from "@/hooks/useCommon";
import FormDialog from "@/components/FormDialog.vue";
import FormDrawer from "@/components/FormDrawer.vue";
import { energyTypeList } from "@/enum/index";
import { disAutoConnect, hiprint } from "vue-plugin-hiprint";
import mb from "../json/mb.json";
import { finishRepairOrderApi, getCarRepairOrderApi, payRepairOrderApi } from "@/api/examine";
import { toast, upperMoney } from "@/utils/index";

const emits = defineEmits(["success"]);

// 打印-取消自动连接
disAutoConnect();
const useRepair = useRepairStore();
// 当前选择维修单信息
const curInfo = ref<any>({});
// 详情
const { formDrawerRef, handleCreate } = useInitForm({});
// 当前服务项目和配件
const curProjectAccessoryList = ref<any[]>([]);

// 项目合计
const handleTotalPrice = () => {
  let totalPrice = 0;
  curProjectAccessoryList.value.forEach((item) => {
    totalPrice += item.totalManHourAmount;
  });
  return totalPrice;
};

// 完工
const handleFinishOrder = async () => {
  if (!curProjectAccessoryList.value.length) {
    return toast("至少要添加一个服务项目", "error");
  }
  try {
    await finishRepairOrderApi({ orderId: curInfo.value.id });
    (formDrawerRef.value as any).close();
    emits("success");
  } catch (error) {
    console.log(error);
  }
};

const handleGetCar = async () => {
  try {
    await getCarRepairOrderApi({ orderId: curInfo.value.id });
    (formDrawerRef.value as any).close();
    emits("success");
  } catch (error) {
    console.log(error);
  }
};

// 打印
const orderPrint = () => {
  let aList: any[] = [];
  const pItem = curProjectAccessoryList.value.map((item: any) => {
    item.productList && aList.push(...item.productList);
    return {
      pname: item.projectName,
      ptype: item.categoryName,
      paccount: item.manHourAmount
    };
  });
  const aItem = aList.map((item: any) => {
    return {
      aname: item.productName,
      aunit: item.unit || "",
      anum: item.num,
      aprice: item.saleAmount,
      aamount: item.totalAmount
    };
  });
  const totalPrice = curInfo.value.totalAmount ? curInfo.value.totalAmount : 0;
  let printData = {
    name: curInfo.value.repairName,
    record: curInfo.value.filingNo,
    orderId: curInfo.value.orderNo, //单号
    orderDate: curInfo.value.createTime, //开单日期
    carname: curInfo.value.customerName,
    carnumber: curInfo.value.licensePlate,
    carphone: curInfo.value.customerPhone,
    cartype: curInfo.value.vehicleModel,
    carkm: curInfo.value.mileageNum + " KM",
    totalPrice,
    totalPriceLarge: upperMoney(totalPrice),
    ptable: pItem,
    atable: aItem
  };
  let hiprintTemplate = new hiprint.PrintTemplate({ template: mb });
  hiprintTemplate.print(printData);
};

// 结算
const {
  formDrawerRef: formDrawerPayRef,
  formRef: formPayRef,
  form: formPay,
  rules: rulesPay,
  handleCreate: handlePayCreate,
  handleSubmit: handlePaySubmit
} = useInitForm({
  form: {
    orderId: "",
    actualAmount: "",
    paySource: ""
  },
  rules: {
    actualAmount: [
      {
        required: true,
        message: "请输入结算金额",
        trigger: "blur"
      }
    ],
    paySource: [
      {
        required: true,
        message: "请选择结算来源",
        trigger: "change"
      }
    ]
  },
  createData: payRepairOrderApi
});
const handlePaySubmitOrder = () => {
  formPay.orderId = curInfo.value.id;
  handlePaySubmit();
  (formDrawerRef.value as any).close();
};

// 处理燃源类型
const handleEnergyType = (val: string | number) => {
  const curItem = energyTypeList.find((item: any) => item.value === val);
  return curItem ? curItem.label : "";
};

// 筛选外观和内饰检查
const outItem = ref<any[]>([]);
const inItem = ref<any[]>([]);
const handleFilterReserve = (value: any) => {
  outItem.value = value.filter((item: any) => item.type === 1);
  inItem.value = value.filter((item: any) => item.type === 2);
};

// 当前选中的维修单
watch(
  () => useRepair.curOrder,
  (newVal) => {
    curInfo.value = newVal;
  },
  {
    immediate: true,
    deep: true
  }
);

// 外观和内饰检查
watch(
  () => useRepair.curReserveInfo,
  (newVal) => {
    handleFilterReserve(newVal);
  }
);

// 服务项目和配件
watch(
  () => useRepair.curProjectAccessoryInfo,
  (newVal) => {
    curProjectAccessoryList.value = newVal;
  }
);

defineExpose({
  handleCreate
});
</script>
<style scoped lang="scss">
.dialog-body {
  height: calc(100vh - 200px);
  overflow-y: auto;
  :deep(.info-label) {
    width: 120px;
    font-weight: 700;
  }
}
</style>
